package com.atguigu.flink.chapter11.function;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2022/1/23 11:06
 */
public class Flink01_Function_Scalar {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
    
        DataStreamSource<WaterSensor> waterSensorStream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50),
                             new WaterSensor("sensor_2", 6000L, 60));
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
    
        Table table = tEnv.fromDataStream(waterSensorStream);
        tEnv.createTemporaryView("sensor", table);
        
        // 1. 在tableAPI中
        // 1.1 内联的方式使用
        /*table
            .select($("id"), call(MyUpperCase.class, $("id")).as("id_upper"))
            .execute()
            .print();*/
        // 1.2 先注册后使用
        /*tEnv.createTemporaryFunction("my_upper", MyUpperCase.class);
        table
            .select($("id"), call("my_upper", $("id")).as("id_upper"))
            .execute()
            .print();*/
        
        // 2. 在sql语句中使用
        tEnv.createTemporaryFunction("my_upper", MyUpperCase.class);
        tEnv.sqlQuery("select id,my_upper(id) from sensor ").execute().print();
        
        
    }
    
    public static class MyUpperCase extends ScalarFunction {
        // 参数的类型和个数, 返回值的类型 根据具体的需求来定.
        // 方法名必须是 eval
        public String eval(String s){
            return s.toUpperCase();
        }
        
    }
}
